import classnames from "classnames";
import { useHistory } from "react-router";
import { NavBar, SearchBar, Dialog } from "antd-mobile";
import Icon from "@/components/Icon";
import styles from "./index.module.scss";
import { useEffect, useState } from "react";
import { useDebounceFn } from "ahooks";
import { useDispatch, useSelector } from "react-redux";
import { clearHistories, deleteHisory, getSuggestion, saveHistory } from "@/store/actions/search";
import { RootState } from "@/types/store";
const SearchPage = () => {
  const history = useHistory();
  const dispatch = useDispatch();
  const [keyword, setKeyword] = useState("");
  // 使用ahooks插件实现防抖
  const { run: getSuggest } = useDebounceFn(
    (e: string) => {
      console.log("获取搜索建议", e);
      dispatch(getSuggestion(e));
    },
    {
      wait: 500,
    }
  );
  const onChange = (e: string) => {
    setKeyword(e);
    if (e) {
      getSuggest(e);
      setIsSearching(true);
    } else {
      setIsSearching(false);
    }
    // 清除上一次定时器
    // clearTimeout(timeRef.current);
    //新建定时器
    // timeRef.current = window.setTimeout(() => {
    //   console.log(e);
    // }, 500);
  };
  // 获取完毕从仓库拿到搜索建议列表
  const { suggestion } = useSelector((state: RootState) => state.search);
  // 正则替换高亮函数
  const highLight = (str: string) => {
    return str.replace(new RegExp(keyword, "gi"), (match) => `<span>${match}</span>`);
  };
  // 是否显示搜索
  const [isSearching, setIsSearching] = useState(false);

  // const timeRef = useRef(-1);
  // 组件销毁时清除延时器
  // useEffect(() => {
  //   return () => {
  //     clearTimeout(timeRef.current);
  //   };
  // }, []);

  // 搜索
  const histories = useSelector((state: RootState) => state.search.histories);
  useEffect(() => {});
  const onSearch = (keyword: string) => {
    console.log(keyword);
    // 保存搜索记录
    if (!keyword) return;
    dispatch(saveHistory(keyword));

    // 跳转页面
    history.push("/search/result?key=" + keyword);
  };
  // 删除所有搜索记录
  const onClearHistory = () => {
    // 清空历史记录
    Dialog.confirm({
      title: "温馨提示",
      content: "你确定要清空记录吗？",
      onConfirm: function () {
        dispatch(clearHistories());
      },
    });
  };
  // 删除部分历史记录
  const delHistory = (e: React.MouseEvent<HTMLSpanElement, MouseEvent>, value: string) => {
    e.stopPropagation();
    dispatch(deleteHisory(value));
  };
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span onClick={() => onSearch(keyword)} className="search-text">
            搜索
          </span>
        }
      >
        <SearchBar value={keyword} onChange={(e) => onChange(e)} placeholder="请输入关键字搜索" />
      </NavBar>

      <div className="history" style={{ display: isSearching ? "none" : "block" }}>
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={onClearHistory}>
            <Icon type="icon-shanchu" />
            清除全部
          </span>
        </div>

        <div className="history-list">
          {histories.map((item, index) => {
            return (
              <div className="history-item" key={index}>
                <span className="historyLeft" onClick={() => onSearch(item)}>
                  {item}
                </span>
                <span className="historyRight" onClick={(e) => delHistory(e, item)}>
                  <Icon type="icon-guanbi2" />
                </span>
              </div>
            );
          })}
        </div>
      </div>
      <div className={classnames("search-result", { show: isSearching })}>
        {suggestion[0] ? (
          suggestion.map((item, index) => {
            return (
              <div className="result-item" key={index} onClick={() => onSearch(item)}>
                <Icon className="icon-search" type="icon-sousuo2" />
                <div
                  className="result-value text-overflow"
                  dangerouslySetInnerHTML={{
                    __html: highLight(item),
                  }}
                ></div>
              </div>
            );
          })
        ) : (
          <div className="result-item">
            <div className="result-value text-overflow">没有搜索建议</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SearchPage;
